<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="74px">
      <el-form-item label="站点名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入站点名称"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['device:cabinet-type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['device:cabinet-type:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['device:cabinet-type:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="powerBankList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="站点名称" prop="name" align="center" />
      <el-table-column label="营业时间" prop="businessHours" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="经度" prop="longitude" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="纬度" prop="latitude" align="center" />
      <el-table-column label="站点地址" prop="fullAddress" align="center" width="230"/>
      <el-table-column label="站点负责人名称" prop="headName" align="center" />
      <el-table-column label="站点负责人电话" prop="headPhone" align="center" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.status === '1'">正常</el-tag>
          <el-tag type="danger" v-else>停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="费用规则" prop="feeRuleName" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']"></el-button>
          </el-tooltip>
          <!--
          <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="User" @click="handleAuthUser(scope.row)" v-hasPermi="['system:role:edit']"></el-button>
          </el-tooltip>
          -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改柜机类型置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="cabinetTypeRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="柜机编号" prop="cabinetNo">
          <el-input v-model="form.cabinetNo" placeholder="请输入柜机编号" />
        </el-form-item>
        <el-form-item label="柜机名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入柜机名称" />
        </el-form-item>
        <el-form-item label="柜机类型" prop="cabinetTypeId">
          <el-select v-model="form.cabinetTypeId" placeholder="请选择柜机类型" style="width: 100%">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.name"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="总插槽数量" prop="totalSlots">
          <el-input v-model="form.totalSlots" placeholder="请输入总插槽数量" />
        </el-form-item>
        <el-form-item label="空闲插槽数量" prop="freeSlots">
          <el-input v-model="form.freeSlots" placeholder="请输入空闲插槽数量" />
        </el-form-item>
        <el-form-item label="已使用插槽数量" prop="usedSlots">
          <el-input v-model="form.usedSlots" placeholder="请输入已使用插槽数量" />
        </el-form-item>
        <el-form-item label="可用充电宝数量" prop="availableNum">
          <el-input v-model="form.availableNum" placeholder="请输入可用充电宝数量" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { searchPageList, save, getDetailById, deleteByIds } from "@/api/device/station";
import { searchPageList as cabinetTypeSearchPageList } from "@/api/device/cabinetType";
import { ElMessage } from 'element-plus';

// const router = useRouter();
const { proxy } = getCurrentInstance();

const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const loading = ref(true);
const total = ref(0);
const title = ref('');
const open = ref(false);
const ids = ref([]);
const options = ref([])

const powerBankList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cabinetNo: undefined,
    name: undefined,
  },
  rules: {
    cabinetNo: [{ required: true, message: "柜机编号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "柜机名称不能为空", trigger: "blur" }],
    cabinetTypeId: [{ required: true, message: "柜机类型不能为空", trigger: "blur" }],
    totalSlots: [{ required: true, message: "总插槽数量不能为空", trigger: "blur" }],
    freeSlots: [{ required: true, message: "空闲插槽数量不能为空", trigger: "blur" }],
    usedSlots: [{ required: true, message: "已使用插槽数量不能为空", trigger: "blur" }],
    availableNum: [{ required: true, message: "可用充电宝数量不能为空", trigger: "blur" }],
    description: [{ required: true, message: "描述不能为空", trigger: "blur" }],
  },
});
const { queryParams, form, rules } = toRefs(data);

function init() {
  getList();
}

/** 柜机查询 */
function getList() {
  loading.value = true;
  const queryCtx = queryParams.value;
  const params = {
    pageNum: queryCtx.pageNum,
    pageSize: queryCtx.pageSize,
  };
  const data = {
    cabinetNo: queryCtx.cabinetNo,
    name: queryCtx.name
  };
  searchPageList(params, data).then(res => {
    if (!res.success) {
      ElMessage({ message: res.msg, type: 'error', duration: 2 * 1000 });
      return;
    }
    const data = res.data;
    total.value = data.total;
    powerBankList.value = data.rows;
    loading.value = false;
  }).catch(e => {
    console.log(e);
    loading.value = false;
    powerBankList.value = [];
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery() {
  queryParams.value.name = '';
  handleQuery();
}
function handleAdd() {
  cabinetTypeSearchPageList({ pageNum: 1, pageSize: 9999 }, {}).then(res => {
    const ls = res.data.rows;
    if (!ls || ls.length === 0) {
      proxy.$modal.msgError("柜机类型加载失败，请联系管理员！");
      return;
    }
    const ops = []
    ls.forEach(item => {
      const d = {
        name: item.name,
        value: item.id
      }
      ops.push(d);
    })
    options.value = ops;
    reset();
    title.value = '添加柜机';
    open.value = true;
  })
}
function handleUpdate(row) {
  reset();
  title.value = '更新柜机';
  const id = row.id || ids.value[0];
  const requests = []
  requests.push(cabinetTypeSearchPageList({ pageNum: 1, pageSize: 9999 }, {}));
  requests.push(getDetailById(id));
  Promise.all(requests).then((resList) => {
    const ls = resList[0].data.rows;
    if (!ls || ls.length === 0) {
      proxy.$modal.msgError("柜机类型加载失败，请联系管理员！");
      return;
    }
    const ops = []
    ls.forEach(item => {
      const d = {
        name: item.name,
        value: item.id
      }
      ops.push(d);
    })
    options.value = ops;
    form.value = resList[1].data;
    open.value = true;
  })
}
function submitForm() {
  proxy.$refs.cabinetTypeRef.validate((valid) => {
    if (valid) {
      save(form.value).then((res) => {
        open.value = false;
        if (form.id) {
          proxy.$modal.msgSuccess("更新成功");
        } else {
          proxy.$modal.msgSuccess("新增成功");
        }
        getList();
      })
    }
  })
}
function cancel() {
  open.value = false;
  reset();
}
// 重置对话框数据
function reset() {
  form.value = {
    cabinetNo: undefined,
    name: undefined,
    cabinetTypeId: undefined,
    totalSlots: undefined,
    freeSlots: undefined,
    usedSlots: undefined,
    availableNum: undefined,
    description: undefined
  };
}
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除选中的数据项?').then(function () {
    const idList = []
    if (row && row.id) {
      idList.push(row.id);
    } else {
      ids.value.forEach(item => {
        idList.push(item);
      })
    }
    deleteByIds(idList.join(',')).then((res) => {
      if (res.success) {
        proxy.$modal.msgSuccess("删除成功");
        getList();
      }
    })
  })
}
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}
function formatOptions(list) {

}
// 初始化
init();
</script>

<style scoped lang="scss">

</style>